#include <stdlib.h>
#include <string.h>
#include "includes/mylist.h"

mylist *mylist_create(int c, cmp_t cmp) {
    if(cmp == NULL) cmp = strcmp;
    mylist *l = malloc(sizeof(mylist));
    l->size = 0;
    l->capacity = c;
    l->cmp = cmp;
    mylnode *n = malloc(sizeof(mylnode));
    n->pre = n;
    n->next = n;
    n->data = NULL;
    l->head = n;
    return l;
}

int mylist_append(mylist *l, void *d) {
    if(MYLIST_IS_FULL(l)) return 0;
    mylnode *tail = l->head->pre;
    mylnode *n = malloc(sizeof(mylnode));
    n->data = d;
    n->pre = tail;
    n->next = l->head;
    tail->next = n;
    l->head->pre = n;
    l->size++;
    return 1;
}

int mylist_insert_at(mylist *l, void *d, int pos) {
    if(pos > l->size || MYLIST_IS_FULL(l)) return -1;
    mylnode *n = mylist_find_at(l, pos);
    printf("[mylist_insert_at] find: %d\n", *(int *)n->data);
    mylnode *n1 = malloc(sizeof(mylnode));
    n1->data = d;
    n1->pre = n->pre;
    n1->next = n;
    n->pre->next = n1;
    n->pre = n1;
    l->size++;
    return 1;
}

void mylist_delete(mylist *l, mylnode *n) {
    n->pre->next = n->next;
    n->next->pre = n->pre;
    l->size--;
}

mylnode *mylist_delete_at(mylist *l, int pos) {
    mylnode *n = mylist_find_at(l, pos);
    if(n == NULL) return NULL;
    mylist_delete(l, n);
    return n;
}

mylnode *mylist_find(mylist *l, void *d) {
    mylnode *n;
    while ((n = l->head->next) != l->head)
    {
        if(!l->cmp(n->data, d)) return n;
    }
    return NULL;
}

mylnode *mylist_find_at(mylist *l, int pos) {
    if(pos >= l->size) return NULL;
    mylnode *n = l->head->next;
    while (pos--) n = n->next;
    return n;
}
